define([], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', 'config', 'MMWService', '$calculater',
    function ($scope, $rootScope ,$filter, $stateParams, config, $MMWService, $calculater) {
        $scope.init = function(){
            $scope.condition = {
                wo_no: '',
                plot_no: '',
                op_no: ''
            };
            $scope.filterValue = {};
            $scope.PageConfig = {
                page : 0,
                total_page:1,
                page_count : 25
            };
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        $scope.search = function(){
            Not_close_plot_info_get($scope.condition, function(data){
                $scope.filter = {};
                $scope.filterValue = {};
                $scope.plot_info_detail = data;
                if($scope.plot_info_detail.length == 1){
                    $scope.showPlotInfo($scope.plot_info_detail[0]);
                }
            });
        };

        $scope.barcode_plot_no = function(event){
            if(!event || event.keyCode == 13){
                var temp_plot_array = $scope.condition.plot_no.split(';');
                if(temp_plot_array.length == 2){
                    $scope.condition.wo_no = '';
                    $scope.condition.plot_no = temp_plot_array[0];
                    $scope.condition.op_no = temp_plot_array[1];
                    $scope.search();
                } else {
                    $rootScope.showAlert($filter('translate')('common.msg.barcode_foramt_error'));
                }
            }
        };

        $scope.qrcode_plot_no = function(){
            $scope.$root.OpenScanner({
                after : function(result){
                    $scope.condition.plot_no = result.text;
                    $scope.barcode_plot_no();
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                },
                orientation : 'landscape'
            });
        };

        $scope.loadOpNoList = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 23,
                header: [
                    {label:$filter('translate')('common.queryList.op_c'), code:'page_no'},
                    {label:$filter('translate')('common.queryList.op_n'), code:'page_name'}
                ],
                setCondition:function(conditions){
                    conditions.push({column_name:'MONo', query_mode:'0', value:$scope.selectPlotItem.wo_no, merge_condition_model:'AND' });
                    return conditions;
                },
                confirm : function(selectItem){
                    $scope.selectPlotItem.op_no = selectItem.page_no;
                    $scope.selectPlotItem.op_display = selectItem.page_no + ' ' + selectItem.page_name;
                }
            });
        };

        $scope.showPlotInfo = function(item){
            tcSMESGetDataWoInfo(item.wo_no, function(data){
                $scope.selectPlotItem = data;
                var nowdatetime = $filter('date')(new Date(),'yyyy/MM/dd HH:mm:ss');
                $scope.selectPlotItem.plot_no = item.plot_no;
                $scope.selectPlotItem.op_no = item.op_no;
                $scope.selectPlotItem.status = item.status;
                $scope.selectPlotItem.qty = item.qty;
                $scope.selectPlotItem.defect_qty = 0;
                $scope.selectPlotItem.report_datetime = nowdatetime;
                $scope.selectPlotItem.employee_no = '';
                $scope.selectPlotItem.labor_hours = 0;
                $scope.selectPlotItem.labor_hours_detail = [];
                $scope.selectPlotItem.machine_no = '';
                $scope.selectPlotItem.machine_hours = 0;
                $scope.selectPlotItem.machine_hours_detail = [];
                $scope.selectPlotItem.c_datetime_object = {
                    date : nowdatetime.split(' ')[0],
                    time : nowdatetime.split(' ')[1]
                };
            });
        };

        //生產批號狀態過濾
        $scope.openStatusFilter = function(){
            $scope.$root.showSelect({
                title : $filter('translate')('common.msg.plz_select'),
                label : 'display',
                code : 'code',
                order: '$index',
                selectCode : $scope.filterValue.status,
                list : [
                    {display:$filter('translate')('dashboard.workLog.status.all'), code:''},
                    {display:$filter('translate')('dashboard.workLog.status.q'), code:'Q'},
                    {display:$filter('translate')('dashboard.workLog.status.r'), code:'R'},
                    {display:$filter('translate')('dashboard.workLog.status.w'), code:'W'},
                    {display:$filter('translate')('dashboard.workLog.status.c'), code:'C'}
                ],
                confirm : function(item, dialog){
                    $scope.filterValue.status = item.code;
                    dialog.hide();
                }
            });
        };

        $scope.loadEmployeeList = function(){
            $scope.$root.showQueryList({
                key:'employee_no',
                pageRecord:50,
                condition:[
                    {name:$filter('translate')('common.queryList.employee_c'), query_mode:'2', value:$scope.selectPlotItem.employee_no,}
                ],
                header : [
                    {label: $filter('translate')('common.queryList.employee_c'), code:'employee_no'},
                    {label: $filter('translate')('common.queryList.employee_n'), code:'employee_name'}
                ],
                query: function(conditions, feedback){
                    tcSMESGetDataUserInfomation('search', conditions, function(data){
                        feedback(data);
                    });
                },
                confirm: function(selectItem, dialog){
                    dialog.hide();
                    $scope.selectPlotItem.labor_hours_detail.push({
                        employee_no : selectItem.employee_no,
                        employee_name : selectItem.employee_name
                    });
                    $scope.selectPlotItem.employee_no = '';
                    $rootScope.focusById('employee_no');
                },
                notQuery : true
            });
        };

        $scope.employee_add = function(event){
            if(!event || event.keyCode == 13){
                if($scope.selectPlotItem.employee_no != ''){
                    tcSMESGetDataUserInfomation('add', $scope.selectPlotItem.employee_no,
                        function(data){
                            if(data && data.length > 0){
                                $scope.selectPlotItem.labor_hours_detail.push({
                                    employee_no : data[0].employee_no,
                                    employee_name : data[0].employee_name
                                });
                                $scope.selectPlotItem.employee_no = '';
                                $rootScope.focusById('employee_no');
                            }
                        },
                        function(contentData){
                            if(event && event.currentTarget)event.currentTarget.blur();
                            $rootScope.showAlert(contentData.Message, function(){
                                $rootScope.focusById('employee_no');
                            });
                        }
                    );
                } else {
                    if(event && event.currentTarget)event.currentTarget.blur();
                    $rootScope.showAlert($filter('translate')('B0601.msg.employee_no_empty'), function(){
                        $rootScope.focusById('employee_no');
                    });
                }
            }
        };

        $scope.employee_remove = function(index){
            $scope.selectPlotItem.labor_hours_detail.splice(index, 1);
        };

        $scope.loadMachineList = function(){
            $scope.$root.showQueryList({
                key:'machine_no',
                pageRecord:50,
                condition:[
                    {name:$filter('translate')('common.queryList.machine_c'), column_name: 'a.EquipmentNo', query_mode:'2', value:$scope.selectPlotItem.machine_no}
                ],
                header : [
                    {label: $filter('translate')('common.queryList.machine_c'), code:'machine_no'},
                    {label: $filter('translate')('common.queryList.machine_n'), code:'machine_name'}
                ],
                query: function(conditions, feedback){
                    var machine_no = '';
                    if(conditions.length > 0){
                        machine_no = conditions[0].value;
                    }
                    tcSMESGetDataMachineStatus(machine_no, function(data){
                        feedback(data);
                    }, null, conditions);
                },
                confirm: function(selectItem, dialog){
                    dialog.hide();
                    $scope.selectPlotItem.machine_hours_detail.push({
                        machine_no : selectItem.machine_no,
                        machine_name : selectItem.machine_name
                    });
                    $scope.selectPlotItem.machine_no = '';
                    $rootScope.focusById('machine_no');
                },
                notQuery : true
            });
        };

        $scope.machine_add = function(event){
            if(!event || event.keyCode == 13){
                if($scope.selectPlotItem.machine_no != ''){
                    tcSMESGetDataMachineStatus($scope.selectPlotItem.machine_no,
                        function(data){
                            if(data && data.length > 0){
                                $scope.selectPlotItem.machine_hours_detail.push({
                                    machine_no : data[0].machine_no,
                                    machine_name : data[0].machine_name
                                });
                                $scope.selectPlotItem.machine_no = '';
                                $rootScope.focusById('machine_no');
                            }
                        },
                        function(contentData){
                            if(event && event.currentTarget)event.currentTarget.blur();
                            $rootScope.showAlert(contentData.Message, function(){
                                $rootScope.focusById('machine_no');
                            });
                        }
                    );
                } else {
                    if(event && event.currentTarget)event.currentTarget.blur();
                    $rootScope.showAlert($filter('translate')('B0601.msg.machine_no_empty'), function(){
                        $rootScope.focusById('machine_no');
                    });
                }
            }
        };

        $scope.machine_remove = function(index){
            $scope.selectPlotItem.machine_hours_detail.splice(index, 1);
        };

        $scope.cancel = function(){
            $scope.selectPlotItem = undefined;
        };

        $scope.confirm = function(){
            var msg = '';
            if($scope.selectPlotItem.labor_hours_detail.length == 0){
                msg += $filter('translate')('B0601.msg.labor_hours_detail_empty');
            }
            if(msg == ''){
                // 20191206 modify by WeiTing for M#65283 - 使用日期套件更換日期，會強制轉為 GMT 時間格式，所以需要再轉換一次。
                var date = $filter('date')($scope.selectPlotItem.c_datetime_object.date,'yyyy/MM/dd');
                $scope.selectPlotItem.complete_datetime = date + ' ' + $scope.selectPlotItem.c_datetime_object.time;
                Offline_work_report_process($scope.selectPlotItem, function(data){
                    $scope.selectPlotItem = undefined;
                    $rootScope.showToast($filter('translate')('B0601.msg.success'));
                    $rootScope.focusById('plot_no');
                });
            } else {
                $rootScope.showAlert(msg, function(){
                    $rootScope.focusById('employee_no');
                });
            }
        };

        $scope.checkSelect = function(item){
            if($scope.selectPlotItem){
                return ($scope.selectPlotItem.plot_no == item.plot_no)
                    && ($scope.selectPlotItem.op_no == item.op_no)
                    && ($scope.selectPlotItem.status == item.status);
            } else {
                return false;
            }
        };

        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
                var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if((item[key]+'').indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if(PageConfig){
                    PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);
                    if(PageConfig.page >= PageConfig.total_page){
                        PageConfig.page = 0;
                    }
                    var index = PageConfig.page*PageConfig.page_count;
                    return temp_list.slice(index, index+PageConfig.page_count);
                } else {
                    return temp_list;
                }
            } else {
                return list;
            }
        };

        //***TOOLS***
        //生產批資訊查詢
        function Not_close_plot_info_get(condition, callback){
            var query_condition_info = [];
            if(condition.wo_no!=undefined && condition.wo_no!='')
                query_condition_info.push({column_name:'A.MOno', query_mode:'0', value:condition.wo_no, merge_condition_model:'AND' });
            if(condition.plot_no!=undefined && condition.plot_no!='')
                query_condition_info.push({column_name:'A.BaseLotno', query_mode:'0', value:condition.plot_no, merge_condition_model:'AND' });

            $MMWService.pageNumberInfoGet({
                page_mode: 'lot_query_no_process_report',
                query_condition_info:query_condition_info
            }, function(itemList){
                if(callback)
                    callback(itemList);
            });
        }

        //取得工單資訊
        function tcSMESGetDataWoInfo(wo_no, callback){
            $MMWService.pageNumberInfoGet({
                page_mode: 'wo_query_no_process_report',
                query_condition_info:[
                    {column_name:'a.MONO', query_mode:'0', value:wo_no, merge_condition_model:'AND' }
                ]
            }, function(itemList){
                if(itemList && itemList.length > 0){
                    if(callback)
                        callback(itemList[0]);
                }
            });
        }

        //取得使用者資訊
        function tcSMESGetDataUserInfomation(type, employee_no, callback, errorback){
            var content = {
                page_mode: 'user_query_no_process_report',
                query_condition_info:[] // P.S. 此後台搜尋服務如果要搜尋全部人員，query_condition_info條件只能帶回空陣列
            };
            console.log(employee_no);
            if(type === 'search'){ // search(開窗查詢作業人員)
                if(employee_no && employee_no.length > 0 && employee_no != '')
                    content.query_condition_info.push({column_name:'a.USERNO', query_mode:employee_no[0].query_mode, value:employee_no[0].value, merge_condition_model:'AND' });
            } else { // add(旁邊加號輸入作業人員)
                if(employee_no && employee_no != '')
                    content.query_condition_info.push({column_name:'a.USERNO', query_mode:'0', value:employee_no, merge_condition_model:'AND' });
            }
                
            $MMWService.pageNumberInfoGet(content, function(itemList){
                if(callback)
                    callback(itemList);
            }, errorback);
        }

        //取得設備資訊
        function tcSMESGetDataMachineStatus(machine_no, callback, errorback, conditions){
            var content = {
                page_mode: 'machine_query_no_process_report',
                query_condition_info:[]
            };
            if(conditions && machine_no != ''){
                content.query_condition_info.push(
                    {
                        column_name: conditions[0].column_name, 
                        query_mode: conditions[0].query_mode, 
                        value: machine_no, 
                        merge_condition_model: 'AND' 
                    }
                );
            } else if (machine_no && machine_no != '' ) {
                content.query_condition_info.push(
                    {
                        column_name: 'a.EquipmentNo', 
                        query_mode: '2', 
                        value: machine_no, 
                        merge_condition_model: 'AND' 
                    }
                );
            }


            $MMWService.pageNumberInfoGet(content, function(itemList){
                if(callback)
                    callback(itemList);
            }, errorback);
        }


        //回寫製程報工資訊
        function Offline_work_report_process(plotItem, callback){
            var content = {
                offline_work_report_detail:[plotItem]
            };
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.offline_work_report_process',
                content : content,
                success : function(data){
                    if(callback)
                        callback(data);
                }
            });
        }
    }
];});
